<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  Delete,
  Search,
  Refresh,
  Upload
} from '@element-plus/icons-vue'
import {
  getCityList,
  getCityDetail,
  createCity,
  updateCity,
  deleteCity,
  batchDeleteCities
} from '@/api/city'
import { uploadFile } from '@/api/upload'
import pcData from '@/assets/pc.json'

// 数据列表
const tableData = ref([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  sortBy: 'created_at',
  sortOrder: 'desc'
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('') // 'add' 或 'edit'
const uploadingImage = ref(false)

// 表单数据
const form = reactive({
  id: null,
  name: '',
  description: '',
  image: '',
  tags: [],
  rating: 0,
  views: 0,
  recommendations: 0,
  bestSeason: '',
  recommendedDays: '',
  attractions: []
})

// 单城市选择（来源于 pc.json，合并所有省份的城市/区县）
const allCities = Array.from(
  new Set(
    Object.values(pcData)
      .filter(v => Array.isArray(v))
      .flat()
  )
)

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入城市名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入城市描述', trigger: 'blur' }]
}

// 标签输入
const tagInput = ref('')
const attractionInput = ref('')

// 选择的行
const multipleSelection = ref([])

// 封面图片文件列表
const coverImageList = ref([])

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      sortBy: searchForm.sortBy,
      sortOrder: searchForm.sortOrder
    }

    const res = await getCityList(params)
    if (res.success) {
      tableData.value = res.data
      if (res.pagination) {
        pagination.page = res.pagination.page
        pagination.pageSize = res.pagination.pageSize
        pagination.total = res.pagination.total
      }
    } else {
      ElMessage.error(res.message || '获取城市列表失败')
    }
  } catch (error) {
    console.error('加载城市列表失败:', error)
    ElMessage.error('加载城市列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.sortBy = 'created_at'
  searchForm.sortOrder = 'desc'
  pagination.page = 1
  loadData()
}

// 分页改变
const handlePageChange = (page) => {
  pagination.page = page
  loadData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 排序改变
const handleSortChange = ({ prop, order }) => {
  if (prop && order) {
    searchForm.sortBy = prop
    searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    loadData()
  }
}

// 打开添加对话框
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '添加城市'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑城市'
  try {
    const res = await getCityDetail(row.id)
    if (res.success) {
      Object.assign(form, res.data)
      // 设置封面图片
      if (form.image) {
        coverImageList.value = [
          {
            url: form.image
          }
        ]
      }
      // 编辑时城市名称已在 form.name 中，直接用于下拉选中
      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取城市详情失败')
    }
  } catch (error) {
    console.error('获取城市详情失败:', error)
    ElMessage.error('获取城市详情失败')
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除城市 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteCity(row.id)
        if (res.success) {
          ElMessage.success('删除成功')
          loadData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      // 用户取消
    })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的城市')
    return
  }

  const cityNames = multipleSelection.value.map((item) => item.name).join('、')
  ElMessageBox.confirm(
    `确定要删除 ${multipleSelection.value.length} 个城市（${cityNames}）吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const ids = multipleSelection.value.map((item) => item.id)
        const res = await batchDeleteCities(ids)
        if (res.success) {
          ElMessage.success(res.message || '批量删除成功')
          multipleSelection.value = []
          loadData()
        } else {
          ElMessage.error(res.message || '批量删除失败')
        }
      } catch (error) {
        console.error('批量删除失败:', error)
        ElMessage.error('批量删除失败')
      }
    })
    .catch(() => {
      // 用户取消
    })
}

// 选择改变
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.name = ''
  form.description = ''
  form.image = ''
  form.tags = []
  form.rating = 0
  form.views = 0
  form.recommendations = 0
  form.bestSeason = ''
  form.recommendedDays = ''
  form.attractions = []
  coverImageList.value = []
  tagInput.value = ''
  attractionInput.value = ''
}

// 提交表单
const handleSubmit = async () => {
  try {
    const data = { ...form }
    // 不允许在管理端设置浏览量/推荐数，提交时移除
    delete data.views
    delete data.recommendations

    let res
    if (dialogType.value === 'add') {
      res = await createCity(data)
    } else {
      res = await updateCity(form.id, data)
    }

    if (res.success) {
      ElMessage.success(
        res.message || (dialogType.value === 'add' ? '添加成功' : '更新成功')
      )
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 处理封面图片上传
const handleCoverChange = async (file, fileList) => {
  if (!file.raw) return

  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    fileList.pop()
    return
  }

  // 验证文件大小
  const isLt5M = file.raw.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB')
    fileList.pop()
    return
  }

  uploadingImage.value = true
  try {
    // 使用导入的 uploadFile 函数，重命名参数避免冲突
    const res = await uploadFile(file.raw)
    if (res.success) {
      form.image = res.data.url
      file.url = res.data.url
      ElMessage.success('封面上传成功')
    } else {
      throw new Error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传封面失败:', error)
    ElMessage.error('上传封面失败: ' + error.message)
    fileList.pop()
  } finally {
    uploadingImage.value = false
  }
}

// 处理封面图片移除
const handleCoverRemove = () => {
  form.image = ''
  coverImageList.value = []
}

// 添加标签
const handleAddTag = () => {
  if (tagInput.value.trim()) {
    if (!form.tags.includes(tagInput.value.trim())) {
      form.tags.push(tagInput.value.trim())
    }
    tagInput.value = ''
  }
}

// 删除标签
const handleRemoveTag = (tag) => {
  const index = form.tags.indexOf(tag)
  if (index > -1) {
    form.tags.splice(index, 1)
  }
}

// 添加景点
const handleAddAttraction = () => {
  if (attractionInput.value.trim()) {
    if (!form.attractions.includes(attractionInput.value.trim())) {
      form.attractions.push(attractionInput.value.trim())
    }
    attractionInput.value = ''
  }
}

// 删除景点
const handleRemoveAttraction = (attraction) => {
  const index = form.attractions.indexOf(attraction)
  if (index > -1) {
    form.attractions.splice(index, 1)
  }
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="city-manage">
    <h2 class="page-title">城市管理</h2>

    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索城市名称或描述"
            clearable
            @keyup.enter="handleSearch"
            style="width: 260px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="排序">
          <el-select
            v-model="searchForm.sortBy"
            placeholder="排序字段"
            style="width: 120px"
          >
            <el-option label="创建时间" value="created_at" />
            <el-option label="城市名称" value="name" />
            <el-option label="评分" value="rating" />
            <el-option label="浏览量" value="views" />
            <el-option label="推荐数" value="recommendations" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select v-model="searchForm.sortOrder" style="width: 100px">
            <el-option label="降序" value="desc" />
            <el-option label="升序" value="asc" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="toolbar-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" :icon="Plus" @click="handleAdd"
          >添加城市</el-button
        >
        <el-button
          type="danger"
          :icon="Delete"
          :disabled="multipleSelection.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column label="封面" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 4px"
            />
            <span v-else style="color: #999">无封面</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="城市名称"
          min-width="120"
          sortable="custom"
        />
        <el-table-column
          prop="description"
          label="描述"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="标签" min-width="150">
          <template #default="{ row }">
            <el-tag
              v-for="tag in row.tags"
              :key="tag"
              size="small"
              style="margin-right: 5px"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="rating"
          label="评分"
          width="100"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="views"
          label="浏览量"
          width="100"
          sortable="custom"
        />
        <el-table-column
          prop="recommendations"
          label="推荐数"
          width="100"
          sortable="custom"
        />
        <el-table-column prop="bestSeason" label="最佳季节" width="120" />
        <el-table-column prop="recommendedDays" label="推荐天数" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="城市名称" prop="name">
          <el-select
            v-model="form.name"
            placeholder="请选择城市名称"
            style="width: 100%"
            filterable
            clearable
          >
            <el-option
              v-for="city in allCities"
              :key="city"
              :label="city"
              :value="city"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="城市描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入城市描述"
          />
        </el-form-item>

        <el-form-item label="封面图片">
          <el-upload
           :file-list="coverImageList"
            :auto-upload="false"
            :limit="1"
            list-type="picture-card"
            :on-change="handleCoverChange"
            :on-remove="handleCoverRemove"
            :disabled="uploadingImage"
          >
            <el-icon><Upload /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                {{
                  uploadingImage
                    ? '正在上传...'
                    : '支持 jpg/png/gif，大小不超过 5MB'
                }}
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="标签">
          <div style="width: 100%">
            <div style="margin-bottom: 10px">
              <el-tag
                v-for="tag in form.tags"
                :key="tag"
                closable
                @close="handleRemoveTag(tag)"
                style="margin-right: 8px"
              >
                {{ tag }}
              </el-tag>
            </div>
            <el-input
              v-model="tagInput"
              placeholder="输入标签后按回车添加"
              @keyup.enter="handleAddTag"
              style="width: 100%"
            >
              <template #append>
                <el-button @click="handleAddTag">添加</el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="评分">
          <el-rate v-model="form.rating" show-score />
        </el-form-item>

        <el-form-item label="浏览量">
          <el-input-number v-model="form.views" :min="0" disabled />
        </el-form-item>

        <el-form-item label="推荐数">
          <el-input-number v-model="form.recommendations" :min="0" disabled />
        </el-form-item>

        <el-form-item label="最佳季节">
          <el-input v-model="form.bestSeason" placeholder="例如：春秋季" />
        </el-form-item>

        <el-form-item label="推荐天数">
          <el-input v-model="form.recommendedDays" placeholder="例如：3-5天" />
        </el-form-item>

        <el-form-item label="热门景点">
          <div style="width: 100%">
            <div style="margin-bottom: 10px">
              <el-tag
                v-for="attraction in form.attractions"
                :key="attraction"
                closable
                type="success"
                @close="handleRemoveAttraction(attraction)"
                style="margin-right: 8px"
              >
                {{ attraction }}
              </el-tag>
            </div>
            <el-input
              v-model="attractionInput"
              placeholder="输入景点名称后按回车添加"
              @keyup.enter="handleAddAttraction"
              style="width: 100%"
            >
              <template #append>
                <el-button @click="handleAddAttraction">添加</el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="uploadingImage"
        >
          {{ uploadingImage ? '上传中...' : '确定' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.city-manage {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.search-card,
.toolbar-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.toolbar {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
}
</style>
